<template>
  <div :class="configType" v-if="medals.list.length>0">
    <div v-if="false">{{configType}},{{testData}}</div>
    <h5>
      <img src="~assets/images/shuyezuo@3x.png">
      {{title}}
      <img src="~assets/images/shuyeyou@3x.png">
    </h5>
    <table class="table" cellspacing="5">
      <tbody class="medals">
      <tr v-for="(items,index) in medals.list">
        <td class="relative" v-for="(item,index) in items">
          <div class="border-medals">
            <img :src="item.iconURL" class="one" v-if="typeof(honorCodesOwned[item.honorCode]) !== 'undefined'">
            <template v-else>
              <img src="~assets/images/wen@2x.png" class="one">
              <div style="position: relative;">
                <div class="honor-name">
                  <span>{{item.honorName}}</span>
                </div>
              </div>
            </template>
            <div class="two">{{item.taskDesc}}</div>
            <div class="three">{{item.configValue}}</div>

            <template v-if="item.configType != 'MYXZ'">
              <div class="four">完成任务得</div>
              <div class="five">
                <img src="~assets/images/jun@3x.png">{{item.walletNum}}
              </div>
            </template>

            <template v-if="typeof(honorCodesOwned[item.honorCode]) === 'undefined'">
              <button class="six btn task" v-if="userType == 'self'" @click.stop.prevent="doTask(item)">做任务</button>
            </template>
            <template v-else-if="userType == 'self'">
              <button class="six btn exchange" v-if="item.configType == 'ZXXZ'" v-show="item.showExchange" @click.stop.prevent="doExchange(item)" >去兑换
              </button>
              <div>
                 <button class="six btn share" :data-honorCode="item.honorCode" :data-honorName="item.honorName"
                      :data-iconUrl="item.iconURL" @click.stop.prevent="doShare(item)">向好友炫耀
                 </button>
              </div>
            </template>
            <div v-show="typeof(honorCodesOwned[item.honorCode]) === 'undefined' || item.configType == 'MYXZ'">
              <button class="empty_button">-</button>
            </div>

          </div>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
  import RemoteDAO from 'common/remoteDAO'
  import CommonUtil from 'common/common.util'
  import LocalDAO from 'common/localDAO'
  import Constant from 'common/constant'
  import _ from 'underscore'

  export default {
    data () {
      return {
        medals: {list: []}, //所有已获得或未获得的勋章
        honorCodesOwned: {},// 已获取的勋章，honorCodes对象,用于比较全部勋章中哪些是已获得的
        userCode: LocalDAO.getUserCode(),
        testData: 'testData',
        error: ''
      }
    },
    props: {
      userType: {
        type: String
      },
      configType: {
        type: String
      },
      title: {
        type: String
      }
    },
    created: function () {
      this.fetchData()
    },
    methods: {
      fetchData () {
        var self = this;
        var medalsOwned = {list: []};
        var honorCodesOwned = {};
        if (self.userType == Constant.user.SELF) {
          medalsOwned = LocalDAO.getMedalsOwned();
        } else if (self.userType == Constant.user.OTHER) {
          medalsOwned = LocalDAO.getOtherMedalsOwned()
        }
        _.each(medalsOwned.list, function (item, index) {
          honorCodesOwned[item.medalCode] = item.medalName;
        });
        self.honorCodesOwned = honorCodesOwned;

        //查询某种类的所有勋章
        RemoteDAO.callUC12000042(self.userCode, self.configType, function (response) {
          if (Number(response.error) === 0) {
            var list = [];
            _.each(response.data.body, function (item, index) {
              var i = Math.floor(index / 3);
              if (typeof list[i] === "undefined") {
                list[i] = [];
              }
              var object = {};
              object.iconURL = item.ICON_URL;
              object.honorName = item.HONOR_NAME;
              object.honorCode = item.HONOR_CODE;
              object.configType = item.CONFIG_TYPE;
              object.showExchange = true;
              try {
                object.walletNum = JSON.parse(item.CONFIG_VALUE).WALLET_NUM;
                object.taskDesc = JSON.parse(item.CONFIG_VALUE).TASK_DESC;
              } catch (error) {
                self.$store.dispatch('setTip', {text: error});
              }
              list[i].push(object);
            });
            self.medals.list = list;

            // 更新分享页数据
            var shareMedalsWall = LocalDAO.getShareMedalsWall();
            switch (self.configType) {
              case "MYXZ":
                shareMedalsWall.medals.myxzList = self.medals;
                break;
              case "ZXXZ":
                shareMedalsWall.medals.zxxzList = self.medals;
                break;
              case "THXZ":
                shareMedalsWall.medals.thxzList = self.medals;
                break;
            }
            shareMedalsWall.honorCodesOwned = self.honorCodesOwned;
            LocalDAO.setShareMedalsWall(shareMedalsWall);
          } else {
            self.$store.dispatch('setTip', {text: response.data});
          }
        });

      },
      doTask (item) {
        var self = this;
        var honorCode = item.honorCode;
        switch (honorCode) {
          case "CCML": // 初出茅庐：上传真实头像
            RemoteDAO.callNativeSetHeader(function (response) {
              if (response.error == "0") {
                window.location.reload(true);
              }
            });
            break;
          case "CSND": // 初试牛刀：不限比赛类型赢得第一场比赛（排进前50%）
            self.$router.push({path: '/game'});
            break;
          case "DGWZ": // 德高望重：累计被10位用户订阅
            self.$router.push({path: '/fans'});
            break;
          case "GGMJ": // 高歌猛进：上牛人榜30名内
            self.$router.push({path: '/greatman/bestmanbox'});
            break;
          case "GLZZ": // 股林至尊：上牛人榜3名内
            self.$router.push({path: '/greatman/bestmanbox'});
            break;
          case "ZQTN": // 壮气吞牛：上牛人榜50名内
            self.$router.push({path: '/greatman/bestmanbox'});
            break;
          case "GPMZ": // 高朋满座：邀请5人注册
            self.$router.push({path: '/selfdetail'});
            break;
          case "GYXK": // 孤影侠客：自己成功开户
            window.location.href = "gtja://sjkh";
            break;
          case "HPHY": // 呼朋唤友：邀请一人开户
            self.$router.push({path: '/selfdetail'});
            break;
          case "ZLTJ": // 崭露头角：上牛人榜100名内
            self.$router.push({path: '/geatman/bestmanboxr'});
            break;
          case "HYCS": // 鸿雁传书：关联自己的好友通讯录
            // window.location.href = "";
            break;
          case "GDQS": // 独孤求胜：比赛累计获胜5次（排进前50%）
            self.$router.push({path: '/game'});
            break;
          case "JJGL": // 技绝股林：上牛人榜10名内
            self.$router.push({path: '/greatman/bestmanbox'});
            break;
          case "GSCQ": // 股市传奇：上组合榜
            self.$router.push({path: '/greatstock/bestgroupbox/'});
            break;
          case "BYTH": // 白银土豪：使用5000积分购买，可送人
            // window.location.href = "";
            break;
          case "QTTH": // 青铜土豪：使用1000积分购买，可送人
            // window.location.href = "";
            break;
        }
      },
      doExchange (item) {
        var self = this;
        var params = {};
        params.wallet_code = item.honorCode;
        params.wallet_num = '1';
        params.ex_wallet_code = "JYB";
        RemoteDAO.callUC12000325(params, function (response) {
          //self.testData = JSON.stringify(response);
          if (Number(response.error) === 0) {
            item.showExchange = false; //隐藏按钮

            //改变君元宝数
            var walletTotal = Number(LocalDAO.getWalletTotal()) + Number(item.walletNum);
            LocalDAO.setWalletTotal(walletTotal);
            self.$root.eventHub.$emit('getWalletTotal',walletTotal)

            // 兑换后，更新 localStorage 中的 medalsOwned
            var medalsOwned = LocalDAO.getMedalsOwned();
            _.each(medalsOwned.list, function (item, index) {
              if (item.medalCode == item.honorCode) {
                medalsOwned.list.splice(index, 1);
                return false;
              }
            });
            LocalDAO.setMedalsOwned(medalsOwned);

            // 兑换后，更新分享页数据
            var shareMedalsWall = LocalDAO.getShareMedalsWall();
            self.$delete(self.honorCodesOwned,item.honorCode);
            shareMedalsWall.honorCodesOwned = self.honorCodesOwned;
            shareMedalsWall.overview.walletTotal = walletTotal;
            LocalDAO.setShareMedalsWall(shareMedalsWall);
            self.$store.dispatch('setTip', {text: '兑换成功'});
          } else {
            self.$store.dispatch('setTip', {text: response.data});
          }
        });
      },
      doShare (item) {
        var self = this;
        var iconURL = item.iconURL;
        var honorName = item.honorName;

        if (self.userType == Constant.user.SELF) { // 仅分享自己页面的勋章
          // 更新分享页数据
          var shareMedal = LocalDAO.getShareMedal();
          shareMedal.overview = {nickname: LocalDAO.getNickname(), userHead: LocalDAO.getUserHead(), iconURL: iconURL, honorName: honorName, walletTotal: LocalDAO.getWalletTotal()};
          LocalDAO.setShareMedal(shareMedal);
        }
        RemoteDAO.sendShareData(Constant.storage.SHARE_MEDAL, function (data) {
          var url = "https://dl.app.gtja.com/nrng/share/" + Constant.storage.SHARE_MEDAL + ".html?userCode=" + self.userCode + "&url=" + data;
          var title = "无敌是多么，多么寂寞";
          var content = "我在牛人牛股，等你来挑战";
          var icon = "https://dl.app.gtja.com/nrng/shareimages/xunzhang.jpg";
          RemoteDAO.share(title, content, url, "title", icon);

          // 埋点
          var object = {};
          object.usercode = self.userCode;
          object.k2 = "";
          TDAPP.onEvent("1005", "", object);
          TDAPP.send();
        });
      }
    }
  }
</script>

<style scoped>

</style>
